package com.nail.api.customMake.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.nail.api.customMake.bean.FileUploadInfo;
import com.nail.api.customMake.bean.Indent;
import com.nail.api.customMake.service.IFileUploadService;
import com.nail.api.customMake.service.IInDentService;
import com.nail.api.user.bean.User;
import com.nail.client.RedisClient;
import com.nail.common.Constant;
import com.nail.controller.BaseController;
import com.nail.utils.IPUtils;
import com.nail.utils.Result4API;
import com.nail.utils.ZipUtils;

@Controller
@RequestMapping("/fileUpload")
public class FileUploadController extends BaseController {

	Logger logger = Logger.getLogger(this.getClass());

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private RedisClient redisClient;

	@Autowired
	private IFileUploadService fileUploadService;

	@Autowired
	private IInDentService inDentService;

	static Map<Integer,Object> orderTypeMap = new HashMap<>();

	static{
		orderTypeMap.put(0,"nail stickers");
		orderTypeMap.put(1,"phone case");
		orderTypeMap.put(2,"nail plates");
	}

	/**
	 * @Fields DEFAULT_TIME_AREA_MILLS : 三个月时间的毫秒数
	 */
	private static final int DEFAULT_TIME_AREA_MILLS = 1000 * 60 * 60 * 24 * 90;

	/**
	 * @Fields DEFAULT_TIME_AREA_SECOND : 三个月时间的秒数
	 */
	private static final int DEFAULT_TIME_AREA_SECOND = 60 * 60 * 24 * 90;

	private String imgRootPath;


	public FileUploadController() throws IOException {
		Properties loadAllProperties = PropertiesLoaderUtils.loadAllProperties("application.yml");
		String property = loadAllProperties.getProperty("imgFilePath");
		imgRootPath = property;
		File file = new File(imgRootPath);
		if (file != null && !file.exists()) {
			file.mkdirs();
		}
	}

	@GetMapping(value = "/img/download/{id}")
	@ResponseBody
	public String downloadImg(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
		if (id == null) {
			return "";
		}
		logger.info(sdf.format(new Date()) + " " + IPUtils.getRemoteHost(request) + ",用户访问了本接口：downloadImg");
		FileUploadInfo img = fileUploadService.getImg(id);
		File file = new File(img.getPath());
		if (file.exists()) {
			FileInputStream fis = null;
			ServletOutputStream outputStream = null;
			try {
				fis = new FileInputStream(file);
				outputStream = response.getOutputStream();
				IOUtils.copy(fis, outputStream);
				outputStream.flush();
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
			} finally {
				IOUtils.closeQuietly(fis);
				IOUtils.closeQuietly(outputStream);
			}
		}
		return null;
	}

	@PostMapping("/img/upload/uploadImgBase64")
	@ResponseBody
	public Result4API uploadImgBase64(String imgList, String token, HttpServletRequest request) {

		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) + " " + IPUtils.getRemoteHost(request) + ",用户访问了本接口：getGoodsPricesById");
		if (StringUtils.isEmpty(imgList) || StringUtils.isEmpty(token)) {
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		try {
			User user = (User) redisClient.get(Constant.REDIS_USER_KEY + token);
			List<FileUploadInfo> uploadInfos = fileUploadService.uploadImgBase64(imgList, user, imgRootPath);
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			result.setData(uploadInfos);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_ERROR);
		}
		return result;
	}

	@GetMapping("/img/down/downZip")
	public void downZip(HttpServletRequest request, HttpServletResponse response, String orderId, String token) throws Exception {

		logger.info(sdf.format(new Date()) + " " + IPUtils.getRemoteHost(request) + ",用户访问了本接口：downZip");
		if (StringUtils.isEmpty(orderId) || StringUtils.isEmpty(token)) {
			return;
		}
		User user = (User) redisClient.get(Constant.REDIS_USER_KEY + token);
		if (user.getRole().getRoleType() != 1) {
			return;
		}
		Indent indent = inDentService.getIndentById(user.getRole().getRoleType() != 1 ?user.getId():null, orderId);
		if(indent == null){
			return;
		}
		OutputStream outputStream = null;
		ZipOutputStream out = null;
		try {
			String zipName = indent.getUserName() + "_" + indent.getOrderNum() + "_img" + ".zip";
			List<FileUploadInfo> fileList = fileUploadService.getFileUploadInfoByOrderId(orderId);//查询数据库中记录
			response.setContentType("APPLICATION/OCTET-STREAM");
			response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
			response.setCharacterEncoding("utf-8");
			outputStream = response.getOutputStream();
			out = new ZipOutputStream(outputStream);
			if(fileList != null){
				for (Iterator<FileUploadInfo> it = fileList.iterator(); it.hasNext(); ) {
					FileUploadInfo file = it.next();
					File filePath = new File(file.getPath());
					if(filePath.exists()){
						ZipUtils.doCompress(file.getPath(), out);
						response.flushBuffer();
					}
				}
			}
			inDentService.setIsDown(orderId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		} finally {
			if(out != null){
				out.close();				
			}
			if(outputStream != null){
				outputStream.close();				
			}
		}
	}


	@GetMapping("/down/downExcel")
	public void downExcel(HttpServletRequest request, HttpServletResponse response, String orderId, String token) throws Exception {

		logger.info(sdf.format(new Date()) + " " + IPUtils.getRemoteHost(request) + ",用户访问了本接口：downExcel");
		if (StringUtils.isEmpty(orderId) || StringUtils.isEmpty(token)) {
			return;
		}
		User user = (User) redisClient.get(Constant.REDIS_USER_KEY + token);
		if (user.getRole().getRoleType() != 1) {
			return;
		}

		try {
			Indent indent = inDentService.getIndentById(user.getRole().getRoleType() != 1 ?user.getId():null, orderId);

			if(indent != null){
				// 创建Excel文档
				HSSFWorkbook wb = new HSSFWorkbook();
				// sheet 对应一个工作页
				HSSFSheet sheet = wb.createSheet("客户订单详情");
				HSSFRow firstrow = sheet.createRow(0);
				// 设置单元格类型
				HSSFCellStyle cellStyle = wb.createCellStyle();
				cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平布局：居中
				// 下标为0的行开始
				HSSFCell[] firstcell = new HSSFCell[12];
				String[] names = new String[12];
				names[0] = "商品名";
				names[1] = "材质";
				names[2] = "图案来源";
				names[3] = "单价";
				names[4] = "数量";
				names[5] = "总价($)";
				names[6] = "是否下载过图案";
				names[7] = "客户备注";
				names[8] = "管理员备注";
				names[9] = "快递公司";
				names[10] = "快递运单号";
				names[11] = "订单号";
				for (int j = 0; j < 12; j++) {
					firstcell[j] = firstrow.createCell((short) j);
					firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
					firstcell[j].setCellStyle(cellStyle);
				}

				// 创建电子表格的一行
				HSSFRow row = sheet.createRow(1);
				HSSFCell[] cells = new HSSFCell[12];
				for (int j = 0; j < 12; j++) {
					cells[j] = row.createCell((short) j);
					cells[j].setCellStyle(cellStyle);
				}
				cells[0].setCellValue(2);
				if (indent.getOrderType() != null) {
					cells[0].setCellValue(new HSSFRichTextString((String) orderTypeMap.get(indent.getOrderType())));
				}
				if (indent.getOrderType() != null && indent.getOrderType() == 1 &&  indent.getPhoneTexture() != null) {
					cells[1].setCellValue(new HSSFRichTextString((String) indent.getPhoneTexture().getName()));
				}

				cells[2].setCellValue(new HSSFRichTextString(indent.getSource() == 0 ?"自定义图案":"模板"));
				cells[3].setCellValue(new HSSFRichTextString(indent.getPrice()+""));
				cells[4].setCellValue(new HSSFRichTextString(indent.getNum()+""));
				cells[5].setCellValue(new HSSFRichTextString(indent.getTotalPrice()+""));
				cells[6].setCellValue(new HSSFRichTextString(indent.getIsDown() == 0?"否":"是"));
				cells[7].setCellValue(new HSSFRichTextString(indent.getMemo()));
				cells[8].setCellValue(new HSSFRichTextString(indent.getAdminMemo()));
				cells[9].setCellValue(new HSSFRichTextString(indent.getExpress()));
				cells[10].setCellValue(new HSSFRichTextString(indent.getWaybill()));
				cells[11].setCellValue(new HSSFRichTextString(indent.getOrderNum()));

				// 创建文件输出流，准备输出电子表格
				response.reset();
				response.setContentType("octets/stream");
				response.addHeader("Content-Disposition", "attachment;filename=" + indent.getUserName() + "_" + indent.getOrderNum()
				+ ".xls");
				OutputStream out = response.getOutputStream();
				wb.write(out);
				out.close();
				response.flushBuffer();

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}

	}

}
